package com.globalresources.ui.struts.action.file;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;

import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.log4j.Logger;

import com.globalresources.business.inface.IDocumentService;
import com.globalresources.business.inface.IFileOperatorService;
import com.globalresources.business.inface.IRelationService;
import com.globalresources.business.inface.IUserService;
import com.globalresources.commons.AbstractAction;
import com.globalresources.commons.Constant;
import com.globalresources.commons.PDFOperate;
import com.globalresources.commons.Pager;
import com.globalresources.commons.PagerService;
import com.globalresources.commons.StringHelper;
import com.globalresources.commons.vo.FileWrapper;
import com.globalresources.po.City;
import com.globalresources.po.DetailUser;
import com.globalresources.po.Document;
import com.globalresources.po.Hospital;
import com.globalresources.po.Relation;
import com.sun.accessibility.internal.resources.accessibility;
import com.sun.java_cup.internal.internal_error;
import com.sun.java_cup.internal.production;

/**
 * @author aaron.lu(luzhiyuan) E-mail:atyuan.lu@gmail.com
 * @since 创建时间：Jul 26, 2009 9:55:43 PM
 */
public class FileAction extends AbstractAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	Logger logger = Logger.getLogger(this.getClass());
	
	private PagerService pagerService;
	private IFileOperatorService fileOperatorService;
	private IRelationService relationService;
	private IDocumentService documentService;
	private IUserService userService;
	
	protected List<FileWrapper> unProcess_filewrappers;
	protected Pager unProcess_pager;
	protected String unProcess_pagerMethod;
	protected String unProcess_totalRow;
	protected String unProcess_currentPage;
	
	protected String hospitalFolder;
	protected List<FileWrapper> under_filewrappers;
	protected Pager under_pager;
	protected String under_pagerMethod;
	protected String under_totalRow;
	protected String under_currentPage;
	
	private String documentName;
	private String createTime;
	protected String position_info;
	protected Document document;
	
	protected List<City> cities;
	protected List<Hospital> hospitals;
	protected Map<Integer, List<Hospital>> hospitalMap;
	protected List<Relation> users;
	protected List<Relation> patients;
	
	protected String filenames;
	protected String[] filenameArray;
	
	protected String receiveTimes;
	protected String[] timeArray;
	
	private String partitionNumber;
	private String partitionPath;
	
	/**
	 * <p>分隔页面
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public String partitionFile(){
		if (StringHelper.isNotEmpty(partitionNumber)) {
			boolean result = false;
			String[] numbers = partitionNumber.split(",");
			try{
				int pageCount = PDFOperate.getPdfPageCount(partitionPath);
				for (int i = 0; i < numbers.length; i++) {
					if (i == 0) {
						result = fileOperatorService.splitFile(partitionPath, 1, Integer.parseInt(numbers[i]));
					}else{
						result = fileOperatorService.splitFile(partitionPath, Integer.parseInt(numbers[i - 1]) + 1, Integer.parseInt(numbers[i]));
					}					
					if(i == (numbers.length - 1)){
						result = fileOperatorService.splitFile(partitionPath, Integer.parseInt(numbers[i]) + 1, pageCount);
					}
				}
			}catch (IOException e) {
				logger.error(e.getMessage());
			}			
			if (result) {
				fileOperatorService.backupFile(partitionPath);
			}
		}
		partitionNumber = null;
		if (!StringHelper.isNotEmpty(filenames)) {
			return "over";
		}
		
		return SUCCESS;
	}
	
	/**
	 * <P>保存文档并剪切文档
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public String save(){
		boolean flag = false;
		try {
			flag = true;
			fileOperatorService.moveFile(fileOperatorService.getHospitalPath()+ "/" + hospitalFolder + "/" + documentName, document.getDetailUserByUserId().getId(), documentName);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		if (flag) {
			documentService.saveDocument(document);
		}		
		document = null;
		return SUCCESS;
	}
	
	/**
	 * <P>统一保存文档
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public String saveAllDocuemt(){
		boolean flag = false;
		try {
			flag = true;
			fileOperatorService.moveFile(fileOperatorService.getHospitalPath()+ "/" + hospitalFolder + "/" + document.getFilename(), document.getDetailUserByUserId().getId(), document.getFilename());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		if (flag) {
			document.setOperateTime(new Date());
			document.setIsSign(Constant.BOOLEAN_FALSE);
			document.setIsView(Constant.BOOLEAN_FALSE);
			Long ct_ = new Long(receiveTimes);
			document.setCreateTime(new Date(ct_));
			Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (null != obj && obj instanceof UserDetails){
				UserDetails userDetails = (UserDetails)obj;
				String userName = userDetails.getUsername();
				DetailUser detailUserByOpeatorId = userService.getUser(userName).get(0).getDetailUser();			
				document.setDetailUserByOpeatorId(detailUserByOpeatorId);
			}	
			documentService.saveDocument(document);
			document = null;
			if(!StringHelper.isNotEmpty(filenames)){
				return "over";
			}
		}
		return SUCCESS;
	}
	
	/**
	 * <P>创建文档页面
	*@author aaron.lu(luzhiyuan)
	*@return
	 * @throws ParseException 
	 */
	public String load() throws ParseException{
		logger.info("loading document info....");
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		document =  new Document();
		document.setIsSign(Constant.BOOLEAN_FALSE);
		document.setIsView(Constant.BOOLEAN_FALSE);
		document.setCreateTime(sd.parse(createTime));
		document.setOperateTime(new Date());
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (null != obj && obj instanceof UserDetails){
			UserDetails userDetails = (UserDetails)obj;
			String userName = userDetails.getUsername();
			DetailUser detailUserByOpeatorId = userService.getUser(userName).get(0).getDetailUser();			
			document.setDetailUserByOpeatorId(detailUserByOpeatorId);
		}		
		document.setFilename(documentName);
		users = relationService.getRelations(null, Constant.AUTHORITY_USER);
		patients = relationService.getRelations(null, Constant.AUTHORITY_PATIENT);
		setCities(fileOperatorService.getCities());
		setHospitals(fileOperatorService.getHospitals());
	    hospitalMap = new HashMap<Integer, List<Hospital>>();
		for (int i = 0; i < hospitals.size(); i++) {
			Hospital hospital = hospitals.get(i);
			Integer city_id = hospital.getCity().getId();
			List<Hospital> list = hospitalMap.get(city_id);
			if (null != list) {
				list.add(hospital);
			}else {
				list = new ArrayList<Hospital>();
				list.add(hospital);
				hospitalMap.put(city_id, list);
			}
		}	
		return SUCCESS;
	}
	
	/**
	 * <P>列出所有文件夹与文件信息
	*@author aaron.lu(luzhiyuan)
	*@return
	*@throws ParseException
	 */
	public String list() throws ParseException{
		List<FileWrapper> _unProcess_filewrappers = fileOperatorService.getAllFilesUnProcess();
		unProcess_pager =  pagerService.getPager(unProcess_currentPage, unProcess_pagerMethod, _unProcess_filewrappers.size());
		unProcess_currentPage = String.valueOf(unProcess_pager.getCurrentPage());
		unProcess_totalRow = String.valueOf(_unProcess_filewrappers.size());
		if(_unProcess_filewrappers.size() < (unProcess_pager.getStartRow() + unProcess_pager.getPageSize())){
			unProcess_filewrappers = _unProcess_filewrappers.subList(unProcess_pager.getStartRow(), _unProcess_filewrappers.size());
		}else{
			unProcess_filewrappers = _unProcess_filewrappers.subList(unProcess_pager.getStartRow(), unProcess_pager.getStartRow() + unProcess_pager.getPageSize());
		}		
		return SUCCESS;
	}
	
	/**
	 * <P>列出某医院下所有文件
	*@author aaron.lu(luzhiyuan)
	*@return
	*@throws ParseException
	 */
	public String listUnderFolder() throws ParseException{
		//position_info = Constant.POSITION_INFO_PREFIX + fileOperatorService.getHospitalPath() +Constant.fs + folder;
		List<FileWrapper> _folder_filewrappers = fileOperatorService.getAllFilesUnderFloder(hospitalFolder);
		under_pager = pagerService.getPager(under_currentPage, under_pagerMethod, _folder_filewrappers.size());
		under_currentPage = String.valueOf(under_pager.getCurrentPage());
		under_totalRow = String.valueOf(_folder_filewrappers.size());
		if (_folder_filewrappers.size() < (under_pager.getStartRow() + under_pager.getPageSize())){
			under_filewrappers = _folder_filewrappers.subList(under_pager.getStartRow(), _folder_filewrappers.size());
		}else{
			under_filewrappers = _folder_filewrappers.subList(under_pager.getStartRow(), (under_pager.getStartRow() + under_pager.getPageSize()));
		}
		return SUCCESS;
	}
	
	/**
	 * <p>分隔文档页面
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public String splitDocument(){
		logger.info(filenames);
		if (StringHelper.isNotEmpty(filenames)) {
			filenameArray = filenames.split(Constant.FILE_NAME_SPLITER);
			String[] name_array = filenameArray;
			timeArray = new String[name_array.length];
			for (int i = 0; i < name_array.length; i++) {
				File file = new File(name_array[i]);
				if (file.exists()) {
				 timeArray[i] = name_array[i] + "," + file.lastModified();
				}
			}
		}		
		return SUCCESS;
	}
	
	/**
	 * <p>同时操作多个文档
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public String operateDocument(){
		if (StringHelper.isNotEmpty(filenames)) {
			String[] name_array = filenames.split(Constant.FILE_NAME_SPLITER);
			timeArray = new String[name_array.length];
			for (int i = 0; i < name_array.length; i++) {
				File file = new File(name_array[i]);
				if (file.exists()) {
				 timeArray[i] = name_array[i] + "," + file.lastModified();
				}
			}
		}
		users = relationService.getRelations(null, Constant.AUTHORITY_USER);
		patients = relationService.getRelations(null, Constant.AUTHORITY_PATIENT);
		setCities(fileOperatorService.getCities());
		setHospitals(fileOperatorService.getHospitals());
		hospitalMap = new HashMap<Integer, List<Hospital>>();
		for (int i = 0; i < hospitals.size(); i++) {
			Hospital hospital = hospitals.get(i);
			Integer city_id = hospital.getCity().getId();
			List<Hospital> list = hospitalMap.get(city_id);
			if (null != list) {
				list.add(hospital);
			}else {
				list = new ArrayList<Hospital>();
				list.add(hospital);
				hospitalMap.put(city_id, list);
			}
		}
		return SUCCESS;
	}

	public PagerService getPagerService() {
		return pagerService;
	}

	public void setPagerService(PagerService pagerService) {
		this.pagerService = pagerService;
	}

	public IFileOperatorService getFileOperatorService() {
		return fileOperatorService;
	}

	public void setFileOperatorService(IFileOperatorService fileOperatorService) {
		this.fileOperatorService = fileOperatorService;
	}

	public List<FileWrapper> getUnProcess_filewrappers() {
		return unProcess_filewrappers;
	}

	public void setUnProcess_filewrappers(List<FileWrapper> unProcess_filewrappers) {
		this.unProcess_filewrappers = unProcess_filewrappers;
	}

	public Pager getUnProcess_pager() {
		return unProcess_pager;
	}

	public void setUnProcess_pager(Pager unProcess_pager) {
		this.unProcess_pager = unProcess_pager;
	}

	public String getUnProcess_pagerMethod() {
		return unProcess_pagerMethod;
	}

	public void setUnProcess_pagerMethod(String unProcess_pagerMethod) {
		this.unProcess_pagerMethod = unProcess_pagerMethod;
	}

	public String getUnProcess_totalRow() {
		return unProcess_totalRow;
	}

	public void setUnProcess_totalRow(String unProcess_totalRow) {
		this.unProcess_totalRow = unProcess_totalRow;
	}

	public String getUnProcess_currentPage() {
		return unProcess_currentPage;
	}

	public void setUnProcess_currentPage(String unProcess_currentPage) {
		this.unProcess_currentPage = unProcess_currentPage;
	}



	public List<FileWrapper> getUnder_filewrappers() {
		return under_filewrappers;
	}

	public void setUnder_filewrappers(List<FileWrapper> under_filewrappers) {
		this.under_filewrappers = under_filewrappers;
	}

	public Pager getUnder_pager() {
		return under_pager;
	}

	public void setUnder_pager(Pager under_pager) {
		this.under_pager = under_pager;
	}

	public String getUnder_pagerMethod() {
		return under_pagerMethod;
	}

	public void setUnder_pagerMethod(String under_pagerMethod) {
		this.under_pagerMethod = under_pagerMethod;
	}

	public String getUnder_totalRow() {
		return under_totalRow;
	}

	public void setUnder_totalRow(String under_totalRow) {
		this.under_totalRow = under_totalRow;
	}

	public String getUnder_currentPage() {
		return under_currentPage;
	}

	public void setUnder_currentPage(String under_currentPage) {
		this.under_currentPage = under_currentPage;
	}

	public String getPosition_info() {
		return position_info;
	}

	public void setPosition_info(String position_info) {
		this.position_info = position_info;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public List<City> getCities() {
		return cities;
	}

	public void setCities(List<City> cities) {
		this.cities = cities;
	}

	public List<Hospital> getHospitals() {
		return hospitals;
	}

	public void setHospitals(List<Hospital> hospitals) {
		this.hospitals = hospitals;
	}

	public Map<Integer, List<Hospital>> getHospitalMap() {
		return hospitalMap;
	}

	public void setHospitalMap(Map<Integer, List<Hospital>> hospitalMap) {
		this.hospitalMap = hospitalMap;
	}

	public IRelationService getRelationService() {
		return relationService;
	}

	public void setRelationService(IRelationService relationService) {
		this.relationService = relationService;
	}

	public List<Relation> getUsers() {
		return users;
	}

	public void setUsers(List<Relation> users) {
		this.users = users;
	}

	public String getDocumentName() {
		return documentName;
	}

	public void setDocumentName(String documentName) {
		this.documentName = documentName;
	}

	public List<Relation> getPatients() {
		return patients;
	}

	public void setPatients(List<Relation> patients) {
		this.patients = patients;
	}

	public IDocumentService getDocumentService() {
		return documentService;
	}

	public void setDocumentService(IDocumentService documentService) {
		this.documentService = documentService;
	}

	public String getCreateTime() {
		return createTime;
	}

	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public Logger getLogger() {
		return logger;
	}

	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	public String getFilenames() {
		return filenames;
	}

	public void setFilenames(String filenames) {
		this.filenames = filenames;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public String[] getFilenameArray() {
		return filenameArray;
	}

	public void setFilenameArray(String[] filenameArray) {
		this.filenameArray = filenameArray;
	}

	public String getReceiveTimes() {
		return receiveTimes;
	}

	public void setReceiveTimes(String receiveTimes) {
		this.receiveTimes = receiveTimes;
	}

	public String[] getTimeArray() {
		return timeArray;
	}

	public void setTimeArray(String[] timeArray) {
		this.timeArray = timeArray;
	}

	public String getPartitionNumber() {
		return partitionNumber;
	}

	public void setPartitionNumber(String partitionNumber) {
		this.partitionNumber = partitionNumber;
	}

	public String getPartitionPath() {
		return partitionPath;
	}

	public void setPartitionPath(String partitionPath) {
		this.partitionPath = partitionPath;
	}

	/**
	 * @return the hospitalFolder
	 */
	public String getHospitalFolder() {
		return hospitalFolder;
	}

	/**
	 * @param hospitalFolder the hospitalFolder to set
	 */
	public void setHospitalFolder(String hospitalFolder) {
		this.hospitalFolder = hospitalFolder;
	}
		
	
	
}


